<template>
  <div class="container">
    <el-card class="app-container">
      <div slot="header" class="clearfix">
        <span>文案管理</span>
      </div>
      <!-- 搜索区域 -->
      <el-form ref="searchForm" label-width="120px" :model="search" class="filter-form">
        <el-row :gutter="5">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="文案标题:">
              <el-input v-model="search.search" size="small" placeholder="请输入文案标题进行模糊搜索" />
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="状态:">
              <el-select v-model="search.status" size="small" placeholder="请选择状态">
                <el-option label="启用" value="1" />
                <el-option label="禁用" value="0" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="8" :lg="6" style="display: flex; justify-content: flex-start;">
            <el-form-item>
              <el-button type="primary" size="medium" @click="handleSearch">查询</el-button>
              <el-button size="medium" @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div style="margin-bottom: 15px; display: flex; justify-content: flex-end;">
        <el-button type="primary" @click="handleAdd">新增文案</el-button>
      </div>

      <!-- 数据表格 -->
      <div style="width: 100%;">
        <el-table
          v-loading="tableloading"
          :data="tableData"
          border
          style="width: 100%"
        >
          <el-table-column prop="id" label="ID" width="80" align="center" />
          <el-table-column prop="title" label="文案标题" align="center" />
          <el-table-column prop="sort_order" label="排序" align="center" />
          <el-table-column prop="status" label="状态" align="center">
            <template slot-scope="scope">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </template>
          </el-table-column>
          <el-table-column prop="create_time" label="创建时间" align="center">
            <template slot-scope="scope">
              {{ formatDate(scope.row.created_at) }}
            </template>
          </el-table-column>
          <el-table-column prop="update_time" label="更新时间" align="center">
            <template slot-scope="scope">
              {{ formatDate(scope.row.updated_at) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160" align="center">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button v-if="scope.row.status === 1" :loading="btnloading && rowId === scope.row.id" type="danger" size="small" @click="handleDisable(scope.row)">禁用</el-button>
              <el-button v-else :loading="btnloading && rowId === scope.row.id" type="success" size="small" @click="handleEnable(scope.row)">启用</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="pagination.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑/新增弹窗 -->
    <el-dialog
      :title="editDialog.data ? '编辑文案' : '新增文案'"
      :visible.sync="editDialog.visible"
      width="35%"
      @close="closeEditDialog"
    >
      <div class="edit-info">
        <el-form ref="editForm" label-width="120px" :model="editForm" :rules="editRules" class="edit-form">
          <el-form-item v-if="editDialog.data" label="文案ID:">
            <span>{{ editDialog.data.id }}</span>
          </el-form-item>
          <el-form-item label="文案标题:" prop="title">
            <el-input v-model="editForm.title" placeholder="请输入文案标题" />
          </el-form-item>
          <el-form-item label="文案图URL:" prop="image">
            <el-input v-model="editForm.image" placeholder="请输入文案图片URL" />
          </el-form-item>
          <el-form-item label="富文本文档:" prop="content">
            <el-input v-model="editForm.content" type="textarea" :rows="5" placeholder="请输入富文本文档内容" />
          </el-form-item>
          <el-form-item label="排序:" prop="sort_order">
            <el-input v-model.number="editForm.sort_order" type="number" placeholder="请输入排序号" />
          </el-form-item>
          <el-form-item label="状态:" prop="status">
            <el-radio-group v-model="editForm.status">
              <el-radio label="1">启用</el-radio>
              <el-radio label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeEditDialog">取消</el-button>
        <el-button :loading="saveLoading" type="primary" @click="handleSave">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getWritingList, getWritingDetail, writingEditAdd, writingEnable } from '@/api/user'
export default {
  data() {
    return {
      search: {
        search: null,
        status: null
      },
      tableData: [],
      pagination: {
        page: 1,
        pageSize: 10,
        total: 0
      },
      tableloading: false,
      btnloading: false,
      saveLoading: false,
      // 编辑/新增弹窗
      editDialog: {
        visible: false,
        data: null
      },
      // 表单
      editForm: {
        title: '',
        image: '',
        content: '',
        sort_order: 0,
        status: '1'
      },
      rowId: '',
      // 表单验证规则
      editRules: {
        title: [
          { required: true, message: '请输入文案标题', trigger: 'blur' },
          { max: 100, message: '文案标题不能超过100个字符', trigger: 'blur' }
        ],
        image: [
          { required: true, message: '请输入文案图URL', trigger: 'blur' },
          { max: 500, message: '文案图URL不能超过500个字符', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入富文本文档内容', trigger: 'blur' }
        ],
        sort_order: [
          { type: 'number', message: '请输入有效的数字', trigger: 'blur', required: false },
          { validator: (rule, value, callback) => {
            if (value !== undefined && value !== null && value < 0) {
              callback(new Error('排序号不能小于0'))
            } else {
              callback()
            }
          }, trigger: 'blur', required: false }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    formatDate(timestamp) {
      if (!timestamp) return '-' // 如果没有时间戳，返回 '-'或其他占位符

      const date = new Date(timestamp)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    handleSearch() {
      this.pagination.page = 1
      this.fetchData()
    },
    resetSearch() {
      this.search = {
        search: null,
        status: null
      }
      this.handleSearch()
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.pagination.page = val
      this.fetchData()
    },
    // 编辑文案
    async handleEdit(row) {
      try {
        // 调用文案详情接口获取数据
        const res = await getWritingDetail({ id: row.id })
        this.editDialog.data = res.data
        // 填充表单数据
        this.editForm = {
          title: res.data.title || '',
          image: res.data.image || '',
          content: res.data.content || '',
          sort_order: res.data.sort_order || 0,
          status: res.data.status.toString() || '1'
        }
        // 打开编辑弹窗
        this.editDialog.visible = true
      } catch (error) {
        this.$message.error('获取文案详情失败')
        console.error('获取文案详情失败:', error)
      }
    },
    // 新增文案
    handleAdd() {
      // 重置表单数据
      this.editForm = {
        title: '',
        image: '',
        content: '',
        sort_order: 0,
        status: '1'
      }
      // 清除编辑数据
      this.editDialog.data = null
      // 打开弹窗
      this.editDialog.visible = true
    },
    // 关闭编辑弹窗
    closeEditDialog() {
      this.editDialog.visible = false
      this.editDialog.data = null
      // 重置表单
      this.$refs.editForm && this.$refs.editForm.resetFields()
    },
    // 保存编辑/新增
    async handleSave() {
      try {
        // 验证表单
        await this.$refs.editForm.validate()
        this.saveLoading = true
        // 构建表单数据
        const formData = {
          title: this.editForm.title,
          image: this.editForm.image,
          content: this.editForm.content,
          sort_order: this.editForm.sort_order || 0,
          status: parseInt(this.editForm.status)
        }

        // 如果是编辑模式，添加id
        if (this.editDialog.data) {
          formData.id = this.editDialog.data.id
        }

        await writingEditAdd(formData)

        this.$message.success('保存成功')
        this.closeEditDialog()
        this.fetchData() // 重新加载数据
      } catch (error) {
        this.$message.error('保存失败')
        console.error('保存文案失败:', error)
      } finally {
        this.saveLoading = false
      }
    },
    // 禁用文案
    async handleDisable(row) {
      if (this.btnloading === true) {
        return this.$message({
          message: '等待操作完成',
          type: 'warning'
        })
      }

      try {
        this.rowId = row.id
        this.btnloading = true
        await writingEnable({
          id: row.id,
          status: 0
        })
        this.$message.success('禁用成功')
        this.fetchData()
      } catch (error) {
        this.$message.error('禁用失败')
        console.error('禁用文案失败:', error)
      } finally {
        this.btnloading = false
      }
    },
    // 启用文案
    async handleEnable(row) {
      if (this.btnloading === true) {
        return this.$message({
          message: '等待操作完成',
          type: 'warning'
        })
      }

      try {
        this.rowId = row.id
        this.btnloading = true
        await writingEnable({
          id: row.id,
          status: 1
        })
        this.$message.success('启用成功')
        this.fetchData()
      } catch (error) {
        this.$message.error('启用失败')
        console.error('启用文案失败:', error)
      } finally {
        this.btnloading = false
      }
    },
    async fetchData() {
      try {
        // 显示表格加载中状态
        this.tableloading = true
        const queryParams = {
          pageSize: this.pagination.pageSize,
          page: this.pagination.page,
          search: this.search.search,
          status: this.search.status
        }
        // 调用实际的文案列表API
        const res = await getWritingList(queryParams)

        // 检查返回数据结构是否正确
        if (res.data && res.data.list && Array.isArray(res.data.list)) {
          this.tableData = res.data.list
          this.pagination.total = res.data.total || 0
        } else {
          this.tableData = []
          this.pagination.total = 0
        }
      } catch (error) {
        this.$message.error('获取文案列表失败')
        console.error('获取文案列表失败:', error)
        // 设置空数据以避免表格显示异常
        this.tableData = []
        this.pagination.total = 0
      } finally {
        this.tableloading = false
      }
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .el-radio__original {
  display: none !important;
}

::v-deep .el-radio:focus:not(.is-focus):not(:active):not(.is-disabled)
  .el-radio__inner {
  box-shadow: none !important;
}
.filter-form {
  padding: 16px;
  padding-right: 0;
  padding-bottom: 0;
  margin-bottom: 6px;
  .el-select {
    width: 100%;
  }
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
}

.add {
  ::v-deep .el-dialog__body{
    max-height: 600px;
    overflow-y: auto;
  }
  ::v-deep .el-form-item {
    margin-bottom: 8px;
    .el-form-item__error {
      padding-top: 0px;
      transform: translateY(-2px)
    }
    .el-select {
      width: 100%;
    }
  }
}
.xg {
  ::v-deep .el-dialog__body{
    padding: 20px;
  }
}
.xxzf {
  ::v-deep .el-form-item {
    margin-bottom: 8px;
  }
  ::v-deep .el-form-item__error {
    padding-top: 0px;
    transform: translateY(-2px)
  }
  ::v-deep .el-dialog__body {
    padding: 10px 20px 15px;
  }
}
</style>
